//
//  UIButton+LanBTouch.m
//  LanBKit
//
//  Created by 涂浩 on 2020/11/6.
//

#import "UIButton+LanBTouch.h"
#import "LanBSwizzle.h"

static const NSTimeInterval KDefaultTimer = 0;

static char * const timingTimerKey = "timingTimerKey";
static char * const timerIntervalKey = "timerIntervalKey";

@implementation UIButton (LanBTouch)

+(void)load{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        lanB_swizzle_instanceMethod(@selector(sendAction:to:forEvent:), @selector(swizzling_sendAction:to:forEvent:), [UIButton class]);
    });
}

#pragma mark 点击按钮的间隔时间 set和 get 方法
-(void)setTimerInterval:(NSTimeInterval)timerInterval{
    objc_setAssociatedObject(self, &timerIntervalKey, @(timerInterval), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(NSTimeInterval)timerInterval{
    return [objc_getAssociatedObject(self, &timerIntervalKey) doubleValue];
}

#pragma mark 点击按钮的计时 set和 get 方法
-(void)setTimingTimer:(NSTimeInterval)timingTimer{
    objc_setAssociatedObject(self, &timingTimerKey, @(timingTimer), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(NSTimeInterval)timingTimer{
    return [objc_getAssociatedObject(self, &timingTimerKey) doubleValue];
}


#pragma mark 防止暴力点击的方法
-(void)swizzling_sendAction:(SEL)action to:(id)target forEvent:(UIControlEvents *)event{
    //这个是判断是为了防止别的事件也走此方法
    if ([self isKindOfClass:UIButton.class]) {
        self.timerInterval = self.timerInterval == 0 ? KDefaultTimer : self.timerInterval;

        if (NSDate.date.timeIntervalSince1970 - self.timingTimer < self.timerInterval) {
               return;
           }
        if (self.timerInterval > 0) {
               self.timingTimer = NSDate.date.timeIntervalSince1970;
           }
    }
    [self swizzling_sendAction:action to:target forEvent:event];
}

@end
